package cn.xiaoniu.day02.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.MidiDevice;

import cn.xiaoniu.day02.bean.IpBean;

public class IpUtil {
	static List<IpBean> list = loadData();
	
	public static void main(String[] args) {
		/*long strIpToLongIp = strIpToLongIp("1.0.3.255");
		System.out.println(strIpToLongIp);*/
		
		loadData();
	}
	
	/**
	 * 查找数据   1 - 11w
	 */
	@Deprecated
	public static IpBean getBeanByLongIp(long ip){
		//List<IpBean> list = loadData();//???
		for (IpBean ipBean : list) {
			//使用ip匹配 ipbean的起止ip，如果在这个范围段内，则匹配成功
			if(ip<=ipBean.getEndIp()&&ip>=ipBean.getStartIp()){
				return ipBean;
			}
		}
		return null;
	}
	
	/**
	 * 高效的查找
	 * 注意：数据需要有序（）
	 */
	public static IpBean newGetBeanByLongIp(long ip){
		// list 使用的是静态代码块里面的
		int start = 0;
		int end = list.size()-1;
		while(start<=end){
			int middle = (start+end)/2;
			//获取中间值
			IpBean ipBean = list.get(middle);
			//成立的时候
			if(ip<=ipBean.getEndIp()&&ip>=ipBean.getStartIp()){
				return ipBean;
			}
			if(ip<ipBean.getStartIp()){
				end = middle-1;
			}
			if(ip>ipBean.getEndIp()){
				start = middle+1;
			}
		}
		return null;
	}
	
	/**
	 * 加载ip数据到list中
	 */
	public static List<IpBean> loadData(){
		List<IpBean> list = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new FileReader("D:\\data\\ip.txt"));){
			String line = null;
			while((line = br.readLine())!=null){
				//数据的切分
				//1.0.1.0|1.0.3.255|16777472|16778239|亚洲|中国|福建|福州||电信|350100|China|CN|119.306239|26.075302
				String[] split = line.split("\\|");
				long startIp = Long.parseLong(split[2]);
				long endIp = Long.parseLong(split[3]);
				String province = split[6];
				String city = split[7];
				String optioner = split[9];
				IpBean bean = new IpBean();
				bean.set(startIp, endIp, province, city, optioner);
				list.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	/**
	 * stringip 转换为 longip
	 * @param strIp
	 * @return
	 */
	public static long strIpToLongIp(String strIp){
		long newIp = 0L;
		if(strIp==null){
			return 0L;
		}
		String[] split = strIp.split("\\.");
		
		for (int i =0;i<=3;i++) {
			long parseLong = Long.parseLong(split[i]);
			//i = 3   i = 2   8   i = 1 
			newIp |= parseLong << ((3-i)<<3);
		}
		return newIp;
	}

}
